
#include "../general.h"
#include "ppctrl.h"

namespace Controls
{
	BEGIN_EVENT_TABLE(PPCtrl, wxWindow)
		EVT_SIZE(PPCtrl::OnSize)
		EVT_PAINT(PPCtrl::OnPaint)
	END_EVENT_TABLE()

	PPCtrl::PPCtrl(		
		wxWindow *parent, wxWindowID id , 
		const wxPoint& pos, 
		const wxSize& size, 
		long style
		)
		: wxWindow(parent, id, pos, size, style)
	{
	}

	PPCtrl::~PPCtrl()
	{
		ClearAll();
	}

	void PPCtrl::OnSize(wxSizeEvent& event)
	{
		RepositionItems();
		UpdateScrollBars();
	}

	void PPCtrl::OnPaint(wxPaintEvent& event)
	{
		wxPaintDC dc(this);

		wxBrush brush(wxColor(255, 255, 205));
		wxPen pen(wxColor(255, 255, 255), 1, wxSOLID);

		dc.SetPen(wxNullPen);
		dc.SetBrush(brush);
		dc.DrawRectangle(GetClientRect());

		if (m_itemlist.size() > 0)
		{
			dc.SetDeviceOrigin(-GetScrollPos(wxHORIZONTAL), -GetScrollPos(wxVERTICAL));

			std::list<ITEM*>::iterator iter;
			for (iter=m_itemlist.begin(); iter!=m_itemlist.end(); ++iter)
			{
				ITEM* pITEM = *iter;
				if (!pITEM) 
					continue;

				wxRect rect = pITEM->rect;
				TransformL2D(rect);
				if (IsExposed(rect))
				{
					DrawItem(&dc, pITEM);
				}
			}
		}
	}

	void PPCtrl::DrawItem(wxDC* pDC, const ITEM* pITEM)
	{
		if (pITEM->rect.GetWidth()==0 || pITEM->rect.GetHeight()==0)
			return;

		pDC->DrawRectangle(pITEM->rect);
	}

	void PPCtrl::RepositionItems()
	{
		//int w, h;

		//std::list<ITEM*>::iterator iter;
		//for (iter=m_itemlist.begin(); iter!=m_itemlist.end(); ++iter)
		//{
		//	ITEM* pITEM = *iter;
		//	if (!pITEM) continue;


		//}
		//
	}

	void PPCtrl::UpdateScrollBars()
	{
		int w, h;

		w = 0;
		h = 0;

		std::list<ITEM*>::iterator iter;
		for (iter=m_itemlist.begin(); iter!=m_itemlist.end(); ++iter)
		{
			ITEM* pITEM = *iter;
			if (!pITEM) 
				continue;

			if (pITEM->rect.GetRight() > w)
				w = pITEM->rect.GetRight();

			if (pITEM->rect.GetBottom() > h)
				h = pITEM->rect.GetBottom();

		}
		
		
		wxSize size = GetClientSize();
		SetScrollbar(
			wxVERTICAL, 
			GetScrollPos(wxVERTICAL), 
			size.GetHeight(),
			h, 
			false
			);
		SetScrollbar(
			wxSB_HORIZONTAL, 
			GetScrollPos(wxHORIZONTAL), 
			size.GetWidth(), 
			w, 
			false
			);
	}

	void PPCtrl::TransformD2L(wxRect& rect)
	{
		rect.Offset(GetScrollPos(wxHORIZONTAL), GetScrollPos(wxVERTICAL));
	}

	void PPCtrl::TransformD2L(wxPoint& point)
	{
		point.x += GetScrollPos(wxHORIZONTAL);
		point.y += GetScrollPos(wxVERTICAL);
	}

	void PPCtrl::TransformL2D(wxRect& rect)
	{
		rect.Offset(-GetScrollPos(wxHORIZONTAL), -GetScrollPos(wxVERTICAL));
	}

	void PPCtrl::TransformL2D(wxPoint& point)
	{
		point.x -= GetScrollPos(wxHORIZONTAL);
		point.y -= GetScrollPos(wxVERTICAL);
	}

	void PPCtrl::ClearAll()
	{
		std::list<ITEM*>::iterator iter = m_itemlist.begin();
		while (iter != m_itemlist.end())
		{
			wxDELETE((ITEM*)*iter);
			iter ++;
		}
	}
}